<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<meta charset="utf-8">
<head th:include="include :: header('修改文章')"></head>
<link href="https://cdn.bootcss.com/bootstrap-tagsinput/0.8.0/bootstrap-tagsinput.css" rel="stylesheet">
<th:block th:include="include::bootstrap-select-css"/>
<th:block th:include="include::wysiwyg-editor-css"/>

<style>
	.keyinput>.bootstrap-tagsinput {
		width: 100%;
	}

	.keyinput input {
		width: 150px;
	}

	.tagView input {
		display: none;
	}

	.tagView .bootstrap-tagsinput {
		padding: 0;
	}

	.opshow {
		opacity: 1;
	}

	.ophide {
		opacity: 0.5;
	}

	.aimg>img {
		width: 100px;
		height: 100px;
	}
</style>
<body class="white-bg" th:object="${article}">
	<h1 style="display: inline-block;">文章修改</h1>
	<form class="form-horizontal m" id="form-article-edit">
		<input name="articleId" type="hidden" th:field="*{articleId}"
			id="articleId">
		<div class="row" style="padding: 10px">
			<div class="col-md-9">
				<!--   标题 -->
				<div class="form-group">
					<div class="col-sm-12">
						<input class="form-control" type="text" name="articleTitle"
							id="articleTitle" th:field="*{articleTitle}" placeholder="文章标题" />
					</div>
				</div>
				<!-- 固定链接|保存 -->
				<div class="form-group">
					<div class="row" style="padding-left: 15px; padding-right: 15px">
						<div class="col-sm-12">
							<div class="row">
								<div class="col-sm-6">
									<input class="form-control" type="text" name="articleUrl" id="articleUrl"  th:field="*{articleUrl}" placeholder="固定链接"  />
									<span class="help-block m-b-none"><i class="fa fa-info-circle"></i> 相对路径为：<span id="relativeUrl"></span></span>
								</div>
								<div class="col-sm-6">
									<div class="btn-group" role="group" style="margin-top: 10px; float: right; margin-right: 40px;">
										<span class="btn btn-default">草稿</span> <span
											class="btn btn-default">本地缓存</span> <span
											class="btn btn-default" id="addOk">保存</span>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
				<!-- 关键词 -->
				<div class="form-group">
					<div class="col-sm-12 keyinput">
						<input class="form-control" type="text" name="keyword"
							id="articleKey" placeholder="关键词" />
					</div>
				</div>
				<!-- 内容 -->
				<div class="form-group">
					<div class="col-sm-12">
						<input type="hidden" name="articleContent" id="articleContent">
						<div id="editor" th:utext="*{articleContent}"></div>
					</div>
				</div>
			</div>

			<div class="col-md-3">
				<!-- 分类 -->
				<div class="form-group">
					<div class="ibox float-e-margins">
						<div class="ibox-title">
							<h5>选择分类</h5>
							<div class="ibox-tools">
								<a class="close-link"><i class="fa fa-question-circle"
														 title="选择分类"></i></a><a class="add-link" onclick="addCat()"><i
									class="fa fa-plus-circle" title="添加分类"></i></a> <a class="collapse-link"><i
									class="fa fa-chevron-up"></i> </a>
							</div>
						</div>
						<div class="ibox-content" style="display: block;">
							<ul class="list-unstyled">
								<li class="tagView"><input class="form-control" type="text"
									name="cats" id="catInput" /></li>
								<li>
									<div class="input-group" style="padding-top: 10px">
										<input class="form-control" type="text"
											onclick="selectCatTree()" id="treeName" readonly
											th:value="${#arrays.isEmpty(cats)?'':cats[0].catName}"> <span
											class="input-group-addon"><i class="fa fa-search"></i></span>
									</div>
								</li>
							</ul>
						</div>
					</div>
				</div>
				<!-- 标签 -->
				<div class="form-group">
					<div class="ibox float-e-margins">
						<div class="ibox-title">
							<h5>选择标签</h5>
							<div class="ibox-tools">
								<a class="close-link"><i class="fa fa-question-circle"
														 title="最多选择3个标签"></i></a> <a class="add-link" onclick="addTag()"><i
									class="fa fa-plus-circle" title="添加标签"></i></a> <a
									class="collapse-link"><i class="fa fa-chevron-up"></i> </a>
							</div>
						</div>
						<div class="ibox-content" style="display: block;">
							<ul class="list-unstyled">
								<li class="tagView"><input class="form-control" type="text"
														   name="tags" id="tagInput" /></li>
								<li style="padding-top: 10px"><select
										class="selectpicker show-tick form-control"
										data-live-search="true" id="chooseTag" name="chooseTag"
										title="选择标签">
								</select></li>
							</ul>
						</div>
					</div>
				</div>
				<!-- 类型 -->
				<div class="form-group">
					<div class="ibox float-e-margins">
						<div class="ibox-title">
							<h5>文章类型</h5>
							<div class="ibox-tools">
								<a class="collapse-link"><i class="fa fa-chevron-up"></i> </a> <a
									class="close-link"><i class="fa fa-times"></i></a>
							</div>
						</div>
						<div class="ibox-content" style="display: block;">
							<div class="radio-box" th:each="dict : ${@dict.getType('cms_article_type')}">
								<input type="radio" th:id="${dict.dictCode}" name="articleType" th:value="${dict.dictValue}" th:field="*{articleType}">
								<label th:for="${dict.dictCode}" th:text="${dict.dictLabel}"></label>
							</div>
						</div>
					</div>
				</div>
				<!-- 评论 -->
				<div class="form-group">
					<div class="ibox float-e-margins">
						<div class="ibox-title">
							<h5>评论开关</h5>
							<div class="ibox-tools">
								<a class="collapse-link"><i class="fa fa-chevron-up"></i> </a> <a
									class="close-link"><i class="fa fa-times"></i></a>
							</div>
						</div>
						<div class="ibox-content" style="display: block;">
							<label class="radio-inline"> <input type="radio" checked
								name="allowComment" value="1" th:field="*{allowComment}">
								开启
							</label> <label class="radio-inline"> <input type="radio"
								name="allowComment" value="0" th:field="*{allowComment}">
								关闭
							</label>
						</div>
					</div>
				</div>
				<!-- 评论 -->
				<div class="form-group">
					<div class="ibox float-e-margins">
						<div class="ibox-title">
							<h5>转载链接</h5>
							<div class="ibox-tools">
								<a class="close-link"><i class="fa fa-question-circle"
									title="文章来源，不填则为原创"></i></a> <a class="collapse-link"><i
									class="fa fa-chevron-up"></i> </a>
							</div>
						</div>
						<div class="ibox-content" style="display: block;">
							<input class="form-control" type="text" name="reprintUrl"
								th:value=${articleContent} id="reprintUrl" />
						</div>
					</div>
				</div>
				<!-- 缩略图 -->
				<input type="hidden" name="articleImg" id="articleImg"
					th:value=${articleImg}>
				<!-- 文章概况 -->
				<input type="hidden" id="summary" name="articleSummary"
					th:value=${articleSummary} />

			</div>
		</div>
	</form>

	<th:block th:include="include :: footer" />
	<th:block th:include="include::bootstrap-select-js"/>
	<th:block th:include="include::wysiwyg-editor-js"/>
	<script src="https://cdn.bootcss.com/bootstrap-tagsinput/0.8.0/bootstrap-tagsinput.min.js"></script>
	<!-- <script src="https://cdn.bootcss.com/bootstrap-select/1.13.9/js/i18n/defaults-zh_CN.min.js"></script> -->
	<!-- 确认文章 -->
	<script type="text/html" id="okAddModel">
    <div class="form-group" style="padding-top:20px">
			<label class="col-sm-2 control-label">文章预览</label>
			<div class="col-sm-10">
				<textarea class="form-control" rows="3" id="articleSummary" placeholder="文章预览"></textarea>
			</div>
		</div>
    
   <div class="form-group" style="padding-top:80px">
			<label class="col-sm-2 control-label">选择封面</label>
			<div class="col-sm-10 aimg" >   
			</div>  
    </div>
    <div class="form-group text-center">
			<button type="button" class="btn btn-primary" id="saveArticle">保存文章</button>
	</div>
    </script>

	<script type="text/javascript" th:inline="JavaScript">
	 var baseArticle = ctx + "cms/article";
	 var baseTag=ctx + "cms/tag";
	 var baseCat= ctx + "cms/cat";


	 /* 初始化富文本编辑器 */
	 var editor = new FroalaEditor("#editor", {
		 // Set the language code.
		 language: 'zh_cn',
		 imageUploadURL: baseArticle + '/articleImg', //上传到本地服务器

	 });
      $("#addOk").click(function() {
    	 if($("input[name='cats']").val()===''){
			  layer.msg('请选择一个分类',{icon:6})
		  }
      else if($.validate.form("form-article-edit"))
          {
			  //获取编辑内容
			  const editorData = editor.html.get(true);
        layer.open({
        	  title:"确认信息",
        	  area:['600px','400px'],
        	  type: 1,
        	  content: $("#okAddModel").html(),
        	  success:function(){
        		 /*  getImgSrc($(".opshow")); */

        		  //填充图片
        		 var imgs=chooseImg(editorData);
        		  if(imgs.length>0)
        			  {
        			  $.each(imgs,function(i,val){
        				  $(".aimg").append("<img class='ophide' src='"+val+"' />")
        			  })
        			  }
        		  //填充描述
        		  $("#articleSummary").val([[*{articleSummary}]]);
        		  //初始化选择事件
        		  $(".aimg>img").click(function(){
        			  if($(this).hasClass("opshow"))
        		       {$(this).removeClass("opshow");
        		       $(this).addClass("ophide");
        				  return ;
        		       }
        			  if($(this).hasClass("ophide")&&$(".opshow").length<3)
        			  {
        				  $(this).removeClass("ophide");
           		          $(this).addClass("opshow");
           		          return ;
        			  }
        			  else{
        				  layer.msg('最多选择3张',{icon:6})
        			  }
        		  });
        		  //初始化提交
        		   $("#saveArticle").click(function(){
        			  $("#articleImg").val(getImgSrc($(".opshow")).toString());
        			  $("#summary").val($("#articleSummary").val());
        			  $("#articleContent").val(editorData);
        			  $.operate.saveTab(baseArticle+"/edit", $('#form-article-edit').serialize());
        		      layer.closeAll();
        		   });
  						}
  					});
        }
      else{
    	  layer.msg('表单验证未通过', {icon: 6});
      }
      });

      function getImgSrc(dom){
    	   var srcs=[];
    	   $.each(dom, function(i,val){
			   srcs.push("'"+$(this).attr("src")+"'")
    	  });
    	return srcs;
      }

     function chooseImg(str){
    	    var data=[]
    	    //获取img标签
    	    var imgReg = /<img.*?(?:>|\/>)/gi;
    	    //匹配src属性
    	    var srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
    	    var arr = str.match(imgReg);
    	    if(arr==null)
    	    	{return data;}
    	    for (var i = 0; i < arr.length; i++) {
    	     var src = arr[i].match(srcReg);
    	     //获取图片地址
    	     if(src[1]){
    	     data.push(src[1]);
    	     }
    	    }
     return data;
     }

     function chooseSummary(html){
    	 html = html.replace(/<\/?[^>]*>/g,''); //去除HTML tag
    	 html = html.replace(/[ | ]*\n/g,'\n'); //去除行尾空白
    	 html = html.replace(/ /ig,'');//去掉
    	 return html;
     }

    </script>

	<script type="text/javascript" th:inline="JavaScript">
	//初始化参数

	var tags=[[${tags}]],cats=[[${cats}]],keyword=[[*{keyword}]];

	$("#form-article-edit").validate({
		errorPlacement: function(error, element) {
			layer.tips(error.html(),element,{tipsMore: true});
		},
		rules:{
			articleType:{
				required:true
			},
			allowComment:{
				required:true
			},
			reprintUrl:{
				url:true
			},
			articleTitle: {
				required: true,
				remote: {
					url: baseArticle+"/checkArticleTitle",
					type: "post",
					dataType: "json",
					data: {
					"articleId":$("#articleId").val()
					,
						"articleTitle": function () {
							if ($("#catInput").val().length != null) {
								return $.common.trim($("#articleTitle").val());
							} else {
								layer.msg('类别未选', {
									icon: 1,
									time: 1000 //2秒关闭（如果不配置，默认是3秒）
								}, function () {
									layer.closeAll();
								});
								return;
							}
						}
					},
					dataFilter : function(data, type) {
						return $.validate.unique(data);
					}
				}
			}, articleUrl: {
				required: true,
				remote: {
					url: baseArticle+"/checkArticleUrl",
					type: "post",
					dataType: "json",
					data: {
						"articleUrl": function () {
							return $.common.trim($("#articleUrl").val());
						},
						"articleId":$("#articleId").val()
					},
					dataFilter: function (data, type) {
						if (data =="0") {
							$("#relativeUrl").text([[${@config.getKey('cms.article.relative.url')}]]+ "/" + $("#articleUrl").val());
						} else {
							$("#relativeUrl").text("");
						}
						return $.validate.unique(data);
					}
				}
			}
		}
		,
		messages : {
			"articleTitle" : {
				remote : "文章标题已经存在"
			},
			"articleUrl" : {
				remote : "文章路径已经存在"
			}
		},
		focusCleanup: true
	});


        /*文章管理-新增-选择类目树*/
        function selectCatTree() {
        	var treeId = $("#treeId").val();
        	var catId = treeId > 0 ? treeId : 1;
        	var url = baseCat+"/selectCatTree/2/" + catId;
			var options = {
				title: '类目选择',
				width: "380",
				url: url,
				callBack: doSubmit
			};
			$.modal.openOptions(options);
		}
       //添加标签
		function doSubmit(index, layero){
			var body = layer.getChildFrame('body', index);
			var catId=body.find('#treeId').val();
			var catName=body.find('#treeName').val();
   			$("#treeName").val(catName);
   			//$('#catInput').tagsinput('removeAll');//不会调用移除事件
   			if($("#catInput").tagsinput('items').length>0)
   				{
   				layer.msg('只允许添加'+$("#catInput").tagsinput('items').length+'个分类', {
					  icon: 1,
					  time: 2000 //2秒关闭（如果不配置，默认是3秒）
					});
   				}
   		    $("#catInput").tagsinput('add',{'catId':catId,'catName':catName});
   			layer.close(index);
		};
	//初始化文章类别
	$("#tagInput").tagsinput({
		maxTags: [[${@config.getKey('cms.tag.maxNum')}]],
		itemValue: 'tagId',
		itemText: 'tagName'
	});
	//初始化文章标签
	$("#catInput").tagsinput({
		maxTags: [[${@config.getKey('cms.cat.maxNum')}]],
		itemValue: 'catId',
		itemText: 'catName'
	});
		 function tagsSync(url,data,ent){
		     return new Promise(function(resolve){
				 $.post(url,data,
						  function(data,status){
						    if(data.code===0)
						    	{
						    	layer.msg('操作成功', {
									  icon: 1,
									  time: 2000 //2秒关闭（如果不配置，默认是3秒）
									});
						    	}
						    else
						    	{
						    	layer.msg('操作失败', {
									  icon: 1,
									  time: 2000 //2秒关闭（如果不配置，默认是3秒）
									});
						    	}
						    resolve(data.code);
						  });
			    });
		 }
		 function tagsEvent(){
			 $('#catInput').on('beforeItemAdd', function(event) {
				 var data={'articleId':$("#articleId").val(),
						 'catId':event.item.catId
				 },url=baseArticle+'/addCatArticle';
				 tagsSync(url,data,event).then(function(res){
	                if(res===0)
	                	{event.cancel;
	                	}
	                else{
	                	$('#catInput').tagsinput('remove', event.item);
	                }
				  });
				});
			 $('#catInput').on('beforeItemRemove', function(event) {
				 var data={'articleId':$("#articleId").val(),
						 'catId':event.item.catId
				 },url=baseArticle+'/removeCatArticle';
				 tagsSync(url,data,event).then(function(res){
	                if(res===0)
	                	{event.cancel
	                	}
	                else{
	                	$('#catInput').tagsinput('remove', event.item);
	                }
				 });
				});
			/* 添加成功后调用*/
			 $('#tagInput').on('beforeItemAdd', function(event) {
				 var data={'articleId':$("#articleId").val(),
						 'tagId':event.item.tagId
				 },url=baseArticle+'/addTagArticle';
				 tagsSync(url,data,event).then(function(res){
		                if(res===0)
		                	{
                                event.cancel
		                	}
		                else{
		                	$('#tagInput').tagsinput('remove', event.item);
		                }
					 });
				});

			 //删除成功后调用
			 $('#tagInput').on('beforeItemRemove', function(event) {
				 var data={'articleId':$("#articleId").val(),
						 'tagId':event.item.tagId
				 },url=baseArticle+'/removeTagArticle';
				 tagsSync(url,data,event).then(function(res){
	                if(res===0)
	                	{
	                	event.cancel
	                	}
	                else{
                        $('#catInput').tagsinput('remove', event.item);
	                }
				 });
				});
		 };
		 function initView(){
			 //初始化标签页
			 if(tags!=null)
			 {
			 $.each(tags,function(i,e){//i是索引，e是json对象
					 $("#tagInput").tagsinput('add',{'tagId':e.tagId,'tagName':e.tagName});
			             });
			 }
			 //初始化类目页
			 if(cats!=null) {
				 $.each(cats, function (i, e) {//i是索引，e是json对象
					 $("#catInput").tagsinput('add', {'catId': e.catId, 'catName': e.catName});
				 });
			 }
			 //初始化标签事件
			 tagsEvent();

		 }
		 initView();

		 $("#articleKey").tagsinput({
			 maxTags: 10
		 });
		 $('#articleKey').tagsinput(
			  "add", keyword
			);
		 //选择标签
		 $("#chooseTag").change(function(){
			 var k=$(this).val();
			 var n=$(this).find("option:selected").text().split("(")[0];
			 if(n!="")
				 {
				 if($("#tagInput").tagsinput('items').length>0)
	   				{
	   				layer.msg('最多允许添加'+$("#tagInput").tagsinput('items').length+'个标签', {
						  icon: 1,
						  time: 2000 //2秒关闭（如果不配置，默认是3秒）
						});
	   				}
			 $("#tagInput").tagsinput('add',{'tagId':k,'tagName':n});
				 }

		 });
	//获取标签列表
	function getTag(){
		$.post(baseTag+"/listvo",function(data,status){
			$("#chooseTag").empty();
			$.each(data,function(i,e){//i是索引，e是json对象
				$("#chooseTag").append("<option value="+e.tagId+">"+e.tagName+"("+((e.tagCount)===null?0:e.tagCount)+")</option>");
			});
			$("#chooseTag").selectpicker("refresh");
		});
	}
		 //初始化下拉
		 $(window).on('load', function () {

		     $('#chooseTag').selectpicker();
			 getTag();

		});

	function addCat() {
		$.modal.open('添加分类',baseCat+"/add/0");
	}

	function addTag() {
		$.modal.open('添加标签',baseTag+"/add");
	}

    </script>
</body>
</html>
